package com.common.client;

import java.util.HashMap;

import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.dom.client.Element;
import com.smartgwt.client.widgets.form.fields.FormItem;

public class KeyboardHandlerRegistrator {
	private static KeyboardHandlerRegistrator registrator = null;
	private HashMap<Integer, HashMap<Integer, Integer>> tmCodes = new HashMap<Integer, HashMap<Integer, Integer>>();

	public synchronized static void registerLanguage(int language_id,
			String codes) {
		if (registrator == null) {
			registrator = new KeyboardHandlerRegistrator();
			createFunction(registrator);
		}
		try {
			String[] each = codes.split(";");
			HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
			for (String code : each) {
				try {
					if (code.trim().length() == 0)
						continue;
					String[] kevalue = code.split(":");

					int key = Integer.parseInt(kevalue[0]);
					int value = Integer.parseInt(kevalue[1]);
					map.put(key, value);
				} catch (Exception e) {
					// TODO: handle exception
				}
			}
			registrator.tmCodes.put(language_id, map);
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	public static void createKeyPressElement(int language_id, FormItem fi) {
		fi.setAttribute("lang_id", language_id);
		fi.setAttribute("usinglang_id", 1);
		fi.setAttribute("onkeypress", "return kepressedevent(event);");
		JavaScriptObject obj = fi.getJsObj();
		if (obj != null) {
			Element elem = (Element) obj;
			if (elem != null)
				System.out.println(elem.getChildCount());
		}
	}

	public static native void createFunction(
			KeyboardHandlerRegistrator registrator)/*-{

													$wnd.keyboardchange = function(l_id, c_code) {
													return registrator.@com.common.client.KeyboardHandlerRegistrator::getCharCode(II)(l_id,c_code);
													};
													$wnd.registerglobal();
													}-*/;

	public int getCharCode(int language_id, int char_code) {
		try {
			HashMap<Integer, Integer> map = tmCodes.get(language_id);
			if (map != null) {
				Integer value = map.get(char_code);
				if (value != null)
					return value.intValue();
			}
		} catch (Exception e) {
			return char_code;
		}
		return char_code;
	}
}
